package com.szly.phm.common.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * 对称加密
 * @author chengjiang
 * @date 
 */
public class AESUtils {

    public final static String CHARSET_UTF8 = "UTF-8";

    /**
     * 加密 plainText加密内容 aseKey密钥
     * @author chengjiang
     * @date 2021/1/18
     */
    public static String encodeText(String plainText, String aseKey) throws Exception {
        // 初始化加密组件.
        var cipher = initAESCipher(aseKey, Cipher.ENCRYPT_MODE);
        // 字节数组加密.
        var cipherBts = cipher.doFinal(plainText.getBytes(CHARSET_UTF8));
        return Base64.encodeBase64URLSafeString(cipherBts);
    }

    /**
     * 解密 cipherText密文（需解密的内容） aseKey密钥
     * @author chengjiang
     * @date 2021/1/18
     */
    public static String decodeText(String cipherText, String aseKey) throws Exception {
            // 初始化解密组件.
            var cipher = initAESCipher(aseKey, Cipher.DECRYPT_MODE);
            // 字节数组解密.
            var result = cipher.doFinal(Base64.decodeBase64(cipherText));
            return new String(result, CHARSET_UTF8);
    }

    /**
     * 初始化AESCipher
     * @author chengjiang
     * @date 2021/1/18
     */
    private static Cipher initAESCipher(String aesKey, int cipherMode) throws Exception {
        var keyGenerator = KeyGenerator.getInstance("AES");
        // 根据传入的随机源sKey初始128位的密钥.
        var secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(aesKey.getBytes());
        keyGenerator.init(128, secureRandom);
        // 生成密钥.
        var secretKey = keyGenerator.generateKey();
        // 获取密钥数组.
        var secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
        var cipher = Cipher.getInstance("AES");
        // 初始化加密后的密码.
        cipher.init(cipherMode, secretKeySpec);
        return cipher;
    }
}
